package chat.keepWind.handle;

import java.awt.Color;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

import chat.keepWind.bean.DataPackage;
import chat.keepWind.ui.ChatUI;
import chat.keepWind.util.ChatUtil;
import chat.keepWind.util.GlobalConst;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class SndFileInboundHandler extends SimpleChannelInboundHandler<DataPackage> {
	
	private int cnt=1; //次数
	
	
	
	@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace(); 
        ctx.close();
    }
	
	@Override
    public void channelRead0(ChannelHandlerContext ctx, DataPackage data) throws Exception {
		String fromIp = data.getFromIp();
    	String toIp = data.getToIp();
    	//发送文件	
		long start = data.getPoint();
        
		RandomAccessFile randomAccessFile = new RandomAccessFile(data.getSrcPath(), "r");
       
        long remain =  data.getFileLen()-start;
        
        if(remain<=0){
        	//没有余下的
        	randomAccessFile.close();
        	
        	String nickName = ChatUtil.getNickName(data.getFromIp());
    		
    		ChatUI chat = ChatUtil.openChat(data.getFromIp(),nickName);
    		Document doc = chat.getDsiplChatArea().getStyledDocument();
    		
    		SimpleAttributeSet headAttr = new SimpleAttributeSet();
    		StyleConstants.setBold(headAttr, true);
    		StyleConstants.setForeground(headAttr, new Color(66, 141, 94));
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		
    		String head = "\n"+nickName+"（"+sdf.format(new Date())+"）"+"：\n";
    		String text = "文件（"+data.getFileName()+"）已接受";
    		try {
    			doc.insertString(doc.getLength(), head,  headAttr);
    			doc.insertString(doc.getLength(), text,  new SimpleAttributeSet());
    		} catch (BadLocationException e) {
    			e.printStackTrace();
    		}
    		//设置 选中的内容，为最后一个字符之后的空字符
    		chat.getDsiplChatArea().setCaretPosition(doc.getLength());
    		
    		/*data.setFlag((byte)1);
        	data.setFromIp(toIp);
        	data.setToIp(fromIp);
	        data.setMsgType(GlobalConst.TYPE_RCV_FILE);
	    	data.setMsgContent("".getBytes(CharsetUtil.UTF_8));//空数据
	        
	        ctx.writeAndFlush(data);*/
        	
            return;
        }
        randomAccessFile.seek(start); //将文件定位到start
        
        byte[] bytes = null;
        if(remain>=GlobalConst.BYTE_NUM){
        	bytes = new byte[GlobalConst.BYTE_NUM];
        }else{
        	bytes = new byte[(int) remain];
        }
       
        randomAccessFile.read(bytes);//读取
        cnt++;
        randomAccessFile.close();
        
        data.setFlag((byte)1);
        data.setFileNo(cnt);
        data.setFromIp(toIp);
    	data.setToIp(fromIp);
        data.setMsgType(GlobalConst.TYPE_RCV_FILE);
    	data.setMsgContent(bytes);
        
        ctx.writeAndFlush(data);
	}
}
